/**
 * Created by gongxun on 16/12/18.
 */

var LoginHelper = function(){
    var that = {};

    //玩家上次微信登录成功后获取的uid
    that.lastWxLoginUid = null;

    //玩家可以用的地址
    that.mRemark = null;

    that.init = function(){
        //读取上次微信登录成功的uid
        that.loadLastWxLoginUid();
    };

    //尝试登录
    that.tryLogin = function(uid){
        if (mo.gameHelper.checkBaseVersion(true)){
            //需要强制升级
            return;
        }

        if (cc.sys.isNative && !mo.gameHelper.isIosCheck){
            mo.showWaitLayer();
            mo.fileHelper.getAccessTokenAndLoginName(function(isExpired, accesstoken, loginname){
                if (isExpired){
                    //微信登录
                    that.wxLogin();
                }else{
                    //通过accesstoken登录
                    that.loginForAccesstoken(accesstoken, loginname, function(isSuccess, code){
                        if (code == 0){
                            //登录成功
                            that.connectServer();
                        }else if (code == 20012 || code == 20064) {
                            //登录过期了 重新唤醒微信
                            that.wxLogin();
                        }else{
                            mo.closeWaitLayer();
                            var showMsg = that.getErrorCode(code);
                            showMsg = "登录失败，" + showMsg;
                            mo.showRoomMsgShow(showMsg);
                            mo.eventHelper.dispatch("login_loginBtnCancel");
                        }
                    });
                }
            });
        }else{
            if (uid == ""){
                mo.showRoomMsgShow("请输入用户名", false);
                return;
            }
            mo.gameWebsocket.openWebSocket(uid);
        }
    };

    //微信登录
    that.wxLogin = function(){
        that.tryGetUserIp(function(tryGetCode){
            if (tryGetCode == 0){
                //唤醒微信完成登录
                mo.nativeHelper.onWxLogin(function(codeType, wxCode, state){
                    if (codeType == 0){
                        mo.httpClient.onWxLogin(wxCode, 0, function(isSuccess, code){
                            if (isSuccess){
                                that.connectServer();
                            }else{
                                mo.closeWaitLayer();
                                var showMsg = that.getErrorCode(code);
                                showMsg = "登录失败，" + showMsg;
                                mo.showRoomMsgShow(showMsg);
                                mo.eventHelper.dispatch("login_loginBtnCancel");
                            }
                        });
                    }else if (codeType == -2){
                        mo.closeWaitLayer();
                        mo.showRoomMsgShow("微信验证失败，用户取消");
                        mo.eventHelper.dispatch("login_loginBtnCancel");
                    }else if (codeType == -4){
                        mo.closeWaitLayer();
                        mo.showRoomMsgShow("微信验证失败");
                        mo.eventHelper.dispatch("login_loginBtnCancel");
                    }
                });
            }else if (tryGetCode == -1){
                //网络连接失败
                mo.showMsgDialogText("连接网络失败，请检查网络连接");
                mo.eventHelper.dispatch("login_loginBtnCancel");
            }
        });
    };

    //通过accesstoken和loginname登录
    that.loginForAccesstoken = function(accesstoken, loginname, func){
        that.tryGetUserIp(function(tryGetCode){
            //向服务器发起token登录 不需要唤起微信
            if (tryGetCode == 0){
                mo.httpClient.onWxConnect(loginname, accesstoken, 0, function(isSuccess, code){
                    func(isSuccess, code);
                });
            }else if (tryGetCode == -1){
                //网络连接失败
                mo.showMsgDialogText("连接网络失败，请检查网络连接");
                mo.eventHelper.dispatch("login_loginBtnCancel");
            }
        });
    };

    //断线重连
    that.reConnet = function(){
        if (cc.sys.isNative && !mo.gameHelper.isIosCheck){
            mo.fileHelper.getAccessTokenAndLoginName(function(isExpired, accesstoken, loginname){
                if (isExpired) {
                    //过期了就重新登录
                    mo.closeWaitLayer();
                    mo.sceneHelper.intoLoginLayer();
                    mo.showMsgDialogText("微信登录验证超时，请重新登录");
                }else{
                    //没有过期 就登录
                    that.tryGetUserIp(function(tryGetCode){
                        if (tryGetCode == 0){
                            mo.httpClient.onWxConnect(loginname, accesstoken, 0, function (isSuccess, code) {
                                mo.closeWaitLayer();
                                if (code == 0){
                                    //登录成功
                                    that.connectServer();
                                }else if (code == 20012 || code == 20064) {
                                    //过期了就重新登录
                                    mo.sceneHelper.intoLoginLayer();
                                    mo.showMsgDialogText("微信登录验证超时，请重新登录");
                                }else{

                                    var showMsg = that.getErrorCode(code);
                                    showMsg = "断线重连失败，" + showMsg + " 是否继续重连？";

                                    //没有连接上依然失败 回到登录界面
                                    mo.showMsgDialogOkAndCancel(showMsg, function(){
                                        mo.eventHelper.dispatch("websocketclose");
                                    }, this, function(){
                                        mo.sceneHelper.intoLoginLayer();
                                    }, this);
                                }
                            });
                        }else if (tryGetCode == -1){
                            //没有连接上依然失败 回到登录界面
                            mo.showMsgDialogOkAndCancel("断线重连失败，请检查网络连接，是否继续重连？", function(){
                                mo.eventHelper.dispatch("websocketclose");
                            }, this, function(){
                                mo.sceneHelper.intoLoginLayer();
                            }, this);

                        }else if (tryGetCode == -2){
                            mo.sceneHelper.intoLoginLayer();
                        }else if (tryGetCode == -3){
                            mo.sceneHelper.intoLoginLayer();
                        }
                    });
                }
            });
        }else{
            //连接网络失败 请重新登录
            mo.gameWebsocket.setClose();
            mo.closeWaitLayer();
            mo.sceneHelper.intoLoginLayer();


            if (mo.gameHelper.isIosCheck){
                var uid = mo.fileHelper.getLoginInfo();
                if (uid == undefined){
                    uid = parseInt(Math.random() * 500 + 1500);
                }
                mo.gameWebsocket.openWebSocket(uid.toString());
            }else{
                mo.showMsgDialogText("连接网络失败，请检查网络连接");
            }
        }
    };

    //登录成功连接服务器
    that.connectServer = function(){
        mo.showWaitLayerNotVisible();

        var uid = mo.nativeConfig.getUid();
        var session = mo.nativeConfig.getSession();

        cc.log("uid:" + uid + " session:" + session);

        //保存这个uid
        that.setLastWxLoginUid(uid);

        mo.gameWebsocket.openWebSocket(uid, session);
    };

    //获取错误代码
    that.getErrorCode = function(code){
        var result = "";
        if (code == -1){
            result = "请检查网络连接";
        }else{
            if (code == 20064 || code == 20008){
                result = "非法请求";
            } else if (code == 20065){
                result = "请确认您的手机系统时间准确";
            } else if (code == 10035){
                result = "请稍后再试";
            } else if (code == 20039){
                result = "请稍后再试";
            } else if (code == 10029){
                result = "请稍后再试";
            } else if (code == 10001){
                result = "请稍后再试";
            } else if (code == 20012){
                result = "请稍后再试";
            } else if (code == 20021){
                result = "你已被禁止登录";
            } else{
                result = "请稍后再试";
            }
        }
        result += ("，错误代码:" + code);
        return result;
    };

    //尝试读取上次微信登录成功的uid
    that.loadLastWxLoginUid = function(){
        var value = mo.fileHelper.getItem("key_LastWxLoginUid");
        if (value != undefined){
            that.lastWxLoginUid = value;
            cc.log("读取lastWxUid成功 uid:" + value);
        }
    };

    //写微信登录成功的uid
    that.getLastWxLoginUid = function(){
        var result = null;
        if (that.lastWxLoginUid != null){
            result = that.lastWxLoginUid;
        }
        return result;
    };

    //读微信登录成功的uid
    that.setLastWxLoginUid = function(uid){
        that.lastWxLoginUid = uid;
        mo.fileHelper.setItem("key_LastWxLoginUid", uid);
    };

    //尝试获取ip并返回结果
    that.tryGetUserIp = function(callBack){
        var code_ok = 0;
        var code_error = -1;
        var code_update = -2;
        var code_kill = -3;

        if (mo.gameHelper.isTestVersion){
            callBack(code_ok);
        }else{
            //尝试获取可用列表
            mo.htmlTools.getCurrentServer(function(isSuccess, infoJson){
                if (isSuccess){

                    //检测可以用的服务器地址
                    var getOnlineServer = function(){
                        //1如果remarks长度为0 那么就提示用户维护中
                        var showKillMsg = "由于出现了网络波动，服务器紧急优化维护中，请稍候再试";
                        if (infoJson.agv.length == 0 && infoJson.ag0.length == 0){
                            mo.eventHelper.dispatch("login_loginBtnCancel");
                            callBack(code_kill);

                            mo.showMsgDialogOk(showKillMsg);
                            return;
                        }

                        //2找到可以玩的ip地址 没找到就告诉用户维护中
                        var isFind = mo.htmlTools.tryFindOnlineIp(infoJson);
                        if (!isFind){
                            mo.eventHelper.dispatch("login_loginBtnCancel");
                            callBack(code_kill);

                            mo.showMsgDialogOk(showKillMsg);
                            return;
                        }

                        // var showMsg = "网址:" + mo.gameHelper.htmlHost + " 网关:" + mo.gameHelper.websocketIpCur;
                        // mo.showMsgDialogText(showMsg);
                        // mo.eventHelper.dispatch("login_loginBtnCancel");
                        // return;
                        callBack(code_ok);
                    };

                    //比较版本号 确定是否升级客户端
                    if (mo.gameHelper.compareVersion(mo.gameHelper.version, infoJson.version)) {
                        mo.eventHelper.dispatch("login_loginBtnCancel");
                        callBack(code_update);

                        mo.showMsgDialogOkAndCancel("检测到最新版本，为了您更好的游戏体验，我们推荐每个用户进行升级\n(点击确定后开始升级)", function(){
                            mo.gameHelper.resetAllProject();
                        }, this, function(){
                            //不升级
                            //检测客户端
                            getOnlineServer();
                        }, this);
                        
                        return;
                    }

                    //检测客户端
                    getOnlineServer();
                }else{
                    //没有获取到 就不管了
                    callBack(code_ok);
                }
            });
        }
    };

    //尝试获取记录
    that.getTryRemark = function(){
        if (that.mRemark == null){
            var remark = mo.fileHelper.getHardServerInfo();
            if (remark != null){
                try{
                    that.mRemark = remark;
                }catch (e){
                    cc.log("errorMsg:" + e);
                }
            }
        }

        return that.mRemark;
    };

    //尝试记录
    that.saveTryRemark = function(remark){
        if (remark != null && remark != ""){
            try {
                mo.fileHelper.setHardServerInfo(remark);
                that.mRemark = remark;
            } catch (e){
                cc.log("errorMsg:" + e);
            }
        }
    };

    //写入登录成功的当前2条信息
    that.saveLastLoginInfo = function(html, ws){
        if (mo.gameHelper.isRead == false){
            return;
        }

        var info = {};
        info.html = html;
        info.ws = ws;
        try {
            var str = JSON.stringify(info);
            cc.log("保存本地logininfo:" + str);
            mo.fileHelper.setLastLoginInfo(str);
        }catch (e){
            cc.log(e);
        }
    };

    //加载上次登录成功数据
    that.loadLastLoginInfo = function(){
        var str = mo.fileHelper.getLastLoginInfo();
        cc.log("读取到本地logininfo:" + str);
        if (str == null){
            return;
        }
        try {
            var info = JSON.parse(str);
            mo.gameHelper.htmlHost = info.html;
            mo.gameHelper.websocketIpCur = info.ws;
        }catch (e){
            cc.log(e);
        }
    };

    return that;
};

mo.loginHelper = new LoginHelper();